import React, { useMemo, useState, useEffect, useCallback } from 'react';
import {
  View,
  Text,
  StyleSheet,
  FlatList,
  TouchableOpacity,
} from 'react-native';
import { useNavigation, useRoute } from '@react-navigation/native';
import Icon from 'react-native-vector-icons/Ionicons';
import AttractionCard from '../components/AttractionCard';
import { locationAPI } from '../api';
import { ToastManager } from '../components/Toast';
import { EmptyState, LoadingIndicator } from '../components/common';
import { parseDistance } from '../utils/helpers';
import {
  COLORS,
  FONT_SIZE,
  FONT_WEIGHT,
  SPACING,
} from '../styles/constants';

/**
 * 当前景区列表页面
 * 显示当前城市的所有景区
 */
export default function ScenicAreaListScreen() {
  const navigation = useNavigation();
  const route = useRoute();
  const { 
    city = '当前城市', 
    cityCode = null,
    scenicAreasData = null, // 从首页传来的当前景区数据
    isCurrentScenic = false, // 是否为当前景区
  } = route.params || {};
  
  const [sortBy, setSortBy] = useState('relevance'); // relevance | rating | distance
  const [loading, setLoading] = useState(!scenicAreasData); // 如果有数据就不需要loading
  const [scenicAreas, setScenicAreas] = useState(scenicAreasData || []);

  // 获取景区列表
  const fetchScenicAreas = useCallback(async () => {
    // 如果已经有传入的景区数据，就不需要调用 API
    if (scenicAreasData && scenicAreasData.length > 0) {
      setLoading(false);
      return;
    }

    try {
      setLoading(true);
      
      const params = {};
      if (cityCode) {
        params.cityCode = cityCode;
      }
      params.pageNum = '1';
      params.pageSize = '100'; // 获取所有景区

      const response = await locationAPI.getOtherScenicAreas(params);
      
      const areas =
        response?.data?.data?.rows ||
        response?.data?.rows ||
        response?.data?.data ||
        response?.data ||
        [];

      setScenicAreas(Array.isArray(areas) ? areas : []);
    } catch (error) {
      console.error('[ScenicAreaList] 获取景区列表失败:', error);
      ToastManager.error('加载失败，请稍后再试');
      setScenicAreas([]);
    } finally {
      setLoading(false);
    }
  }, [cityCode, scenicAreasData]);

  useEffect(() => {
    fetchScenicAreas();
  }, [fetchScenicAreas]);

  // 排序后的景区列表
  const sortedScenicAreas = useMemo(() => {
    const base = scenicAreas || [];
    if (sortBy === 'rating') {
      return [...base].sort((a, b) => (b.rating || 0) - (a.rating || 0));
    }
    if (sortBy === 'distance') {
      return [...base].sort((a, b) => {
        // 兼容两种格式："XXkm" 字符串或 distanceKm 数字
        const distA = a.distance ? parseDistance(a.distance) : (a.distanceKm || 0);
        const distB = b.distance ? parseDistance(b.distance) : (b.distanceKm || 0);
        return distA - distB;
      });
    }
    return base;
  }, [scenicAreas, sortBy]);

  // 转换为卡片数据
  const cardsData = useMemo(
    () =>
      sortedScenicAreas.map((item, index) => ({
        id: String(item.id || item.scenicAreaId || index),
        name: item.areaName || item.name || '-',
        image: item.coverImage || item.image,
        address: item.address,
        rating: item.rating,
        level: item.level,
        type: item.typeName || item.type,
        // 兼容两种数据格式：已经是 "XXkm" 格式 或 distanceKm 数字
        distance: item.distance || (item.distanceKm ? `${item.distanceKm}km` : null),
        raw: item,
      })),
    [sortedScenicAreas],
  );

  return (
    <View style={styles.container}>
      {/* 标题栏 */}
      <View style={styles.header}>
        <TouchableOpacity
          style={styles.backButton}
          onPress={() => navigation.goBack()}
          hitSlop={{ top: 10, bottom: 10, left: 10, right: 10 }}
        >
          <Icon name="arrow-back" size={24} color={COLORS.text.primary} />
        </TouchableOpacity>
        <Text style={styles.title}>
          {isCurrentScenic ? '当前景区' : `${city}的景区`}
        </Text>
        <View style={styles.placeholder} />
      </View>

      {/* 工具栏 */}
      <View style={styles.toolbar}>
        <Text style={styles.resultHint}>
          共 {cardsData.length} 个景区
        </Text>
        <View style={styles.sortRow}>
          <TouchableOpacity onPress={() => setSortBy('relevance')}>
            <Text
              style={[
                styles.sortBtn,
                styles.sortBtnFirst,
                sortBy === 'relevance' && styles.sortActive,
              ]}
            >
              默认
            </Text>
          </TouchableOpacity>
          <TouchableOpacity onPress={() => setSortBy('rating')}>
            <Text
              style={[styles.sortBtn, sortBy === 'rating' && styles.sortActive]}
            >
              评分
            </Text>
          </TouchableOpacity>
          <TouchableOpacity onPress={() => setSortBy('distance')}>
            <Text
              style={[
                styles.sortBtn,
                sortBy === 'distance' && styles.sortActive,
              ]}
            >
              距离
            </Text>
          </TouchableOpacity>
        </View>
      </View>

      {/* 景区列表 */}
      {loading ? (
        <LoadingIndicator text="正在加载..." />
      ) : (
        <FlatList
          data={cardsData}
          keyExtractor={item => item.id}
          contentContainerStyle={
            cardsData.length === 0 ? { flex: 1 } : { paddingBottom: 20 }
          }
          renderItem={({ item }) => {
            const itemData = item.raw || item;
            // 兼容两种数据来源：
            // 1. scenicAreasWithSpots 使用 type 字段（'scenicArea' 或 'scenicSpot'）
            // 2. API 返回使用 areaType 字段（1 或 2）
            let itemType = 'scenicArea';
            if (itemData.type === 'scenicSpot') {
              itemType = 'scenicSpot';
            } else if (itemData.areaType === 2) {
              itemType = 'scenicSpot';
            }
            const areaType = itemType === 'scenicArea' ? 1 : 2;
            
            return (
              <AttractionCard
                item={item}
                onPress={() =>
                  navigation.navigate('AttractionDetail', {
                    attraction: itemData,
                    itemType: itemType,
                    itemId: itemData.id || itemData.scenicAreaId,
                    areaType: areaType,
                  })
                }
              />
            );
          }}
          ListEmptyComponent={
            <EmptyState
              icon="location-outline"
              title="暂无景区"
              message="该城市暂无景区数据"
            />
          }
        />
      )}
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: COLORS.background.primary,
  },
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingHorizontal: SPACING.md,
    paddingTop: 48,
    paddingBottom: 12,
    backgroundColor: COLORS.white,
    borderBottomWidth: 1,
    borderBottomColor: COLORS.border.light,
  },
  backButton: {
    padding: 8,
  },
  title: {
    fontSize: FONT_SIZE.xl,
    fontWeight: FONT_WEIGHT.bold,
    color: COLORS.text.primary,
  },
  placeholder: {
    width: 40,
  },
  toolbar: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingHorizontal: SPACING.md,
    paddingVertical: 12,
    backgroundColor: COLORS.white,
    borderBottomWidth: 1,
    borderBottomColor: COLORS.border.light,
  },
  resultHint: {
    fontSize: FONT_SIZE.sm,
    color: COLORS.text.tertiary,
  },
  sortRow: {
    flexDirection: 'row',
  },
  sortBtn: {
    fontSize: FONT_SIZE.sm,
    color: COLORS.text.tertiary,
    paddingVertical: 4,
    paddingHorizontal: 8,
    marginLeft: 16,
  },
  sortBtnFirst: {
    marginLeft: 0,
  },
  sortActive: {
    color: COLORS.primary,
    fontWeight: FONT_WEIGHT.bold,
  },
});
